import axios from "axios";
import Api from "src/api/Api";
import Taro from '@tarojs/taro';

// 创建 axios 实例
const createAxiosInstance = () => {
    // 访问域名
    const baseURL = "https://gateway.uniqtee.com/h5";
    // 开发模式访问的域名
    const devBaseURL = "/h5";

    // 根据环境选择基础 URL
    const isDev = process.env.NODE_ENV === 'development';
    const selectedBaseURL = isDev ? devBaseURL : baseURL;

    const instance = axios.create({
        baseURL: baseURL,
        timeout: 30000,
        headers: {
            'Content-Type': 'application/json'
        }
    });

    return instance;
};

const http = createAxiosInstance();

// 数据模型定义（所有接口定义已移至文件底部）

// 订单管理API
class TtOrderApi extends Api {
    constructor() {
        super();
        // this.authLogin({
        //     username: 'admin',
        //     password: 'h5-10086'
        // });
    }

    token = "";
    logining = false;
    externalOrderNo = "";
    productSize = "";
    productColor = "";
    sign = "";
    skuId = "";
    productNegativeId = 0;
    authorization = "";

    // 登录接口
    async authLogin() {
        while (this.logining) {
            await new Promise(resolve => setTimeout(resolve, 100));
        }
        if (!this.token) {

            // 解析URL参数
            const urlParams = new URLSearchParams(location.search.replace(/^\?/, '').replace(/\/$/, ''));
            // 将参数复制到this对象
            this.sign = urlParams.get('sign') || '';
            this.token = urlParams.get('token') || '';
            this.externalOrderNo = urlParams.get('externalOrderNo') || '';
            this.productSize = urlParams.get('productSize') || '';
            this.productColor = urlParams.get('productColor') || '';
            this.skuId = urlParams.get('skuId') || '';
            this.productNegativeId = Number(urlParams.get('productNegativeId') || '0');

            console.log('解析后的URL参数:', this);
            debugger;
            // 调用tempTokenExchange方法获取JWT，确保参数不为null
            const tempTokenExchangeRes = await ttOrderApi.tempTokenExchange({
                token: this.token || '',
                sign: this.sign || '',
                extraParams: {
                    externalOrderNo: this.externalOrderNo || '',
                    productSize: this.productSize || '',
                    productColor: this.productColor || '',
                    skuId: this.skuId || '',
                    productNegativeId: this.productNegativeId || 0,
                }
            });
            debugger;
            // 如果返回的code不是200，表示异常状态，抛出错误
            if (tempTokenExchangeRes.data.code !== 200) {
                console.error('API错误:', tempTokenExchangeRes.data.message);
                // 抛出错误，让调用方处理
                throw new Error(tempTokenExchangeRes.data.message || '请求失败');
            }

            debugger;
            console.log('tempTokenExchange result:', tempTokenExchangeRes);
            debugger;
            this.authorization = `Bearer ${tempTokenExchangeRes?.data?.data?.accessToken}`;

            this.logining = false;
        }
    }

    // 生成临时token
    async tempTokenGenerate(params: GenerateTokenRequest) {
        const res = await http.post('/token/generate', params, {
            headers: {
                authorization: this.authorization
            }
        });
        debugger;
        return res;
    }

    // 临时token换取JWT
    async tempTokenExchange(params: ExchangeTokenRequest) {
        const res = await http.post('/token/exchange', params,
            {
                headers: {
                    authorization: this.authorization
                }
            });
        return res;
    }

    // 检查临时token状态
    async tempTokenStatus(token: string) {
        const res = await http.get(`/temp-token/status?token=${token}`, {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 撤销临时token
    async tempTokenRevoke(token: string) {
        const res = await http.post(`/temp-token/revoke?token=${token}`, {}, {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    //根据底板ID查询关联的场景模板列表
    async listByNegativeId(productNegativeId: number) {
        while (!this.authorization) {
            await new Promise(resolve => setTimeout(resolve, 100));
        }
        // return goodsTemlateDataJSON;
        const res = await http.get('/product/negativeTemplate/listByNegativeId', {
            params: {
                productNegativeId,
                pageNum: 1,
                pageSize: 99,
                designLimit: 9,
            },
            headers: {
                authorization: this.authorization
            }
        });
        const goodsTemlateData = res.data.data.records || [];
        goodsTemlateData.forEach(item => {
            item.designs.map(design => {
                if (typeof design.data === 'string') {
                    design.data = JSON.parse(design.data || '{}');
                }
            })
        })
        return goodsTemlateData;
    }



    // 根据底板id查询底板信息
    async getProductNegativeById() {
        while (!this.authorization) {
            await new Promise(resolve => setTimeout(resolve, 100));
        }

        try {
            const response = await http.get<ApiResponse<any>>('/product/negativeTemplate/getProductNegativeById', {
                params: { productNegativeId: this.productNegativeId },
                headers: {
                    authorization: this.authorization
                }
            });

            if (response.data.code !== 200) {
                const errorMessage = response.data.message || '查询底板信息失败';
                throw new Error(errorMessage);
            }

            const goodsBase = response.data.data || {};

            goodsBase.data = JSON.parse(goodsBase.data || '{}');
            goodsBase.suitFor = JSON.parse(goodsBase.suitFor || '[]');
            
            return goodsBase;
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '网络异常，请稍后重试';
            console.error('查询底板信息失败:', error);
            throw error;
        }
    }

    // 底板模板
    // 查询模板列表
    async getTemplateList(productNegativeId: number, pageNum?: number, pageSize?: number) {
        const res = await http.get('/product-negative/template/list', {
            params: {
                productNegativeId,
                pageNum,
                pageSize
            },
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 查询设计数据
    async getDesigns(templateId: number) {
        const res = await http.get(`/product-negative/template/designs?templateId=${templateId}`, {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 设计订单
    // 提交设计
    async submitDesignOrder(params: SubmitDesignRequest) {
        const res = await http.post('/design-order/submit', params, {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 查询订单列表
    async getDesignOrderList(params: {
        currentPage?: number;
        pageSize?: number;
        orderStatus?: number;
        token?: string;
    }) {
        const res = await http.get('/design-order/list', {
            params,
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 查询订单详情
    async getDesignOrderDetail(orderId: number) {
        const res = await http.get(`/design-order/detail?orderId=${orderId}`, {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 取消订单
    async cancelDesignOrder(orderId: number) {
        const res = await http.post(`/design-order/cancel?orderId=${orderId}`, {}, {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 字体管理
    // 根据ID获取字体信息
    async getFontByIds(fontIds: number[]) {
        // 过滤无效ID并去重
        const validFontIds = Array.from(new Set(fontIds.filter(id => id !== undefined && id !== null && id !== 0)));
        const res = await http.get('/font/get-by-ids', {
            params: {
                fontIds: validFontIds.join(',')
            },
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 测试接口
    // 需要认证的接口
    async testAuth() {
        const res = await http.get('/test/auth', {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 公开接口
    async testPublic() {
        const res = await http.get('/test/public', {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 管理员权限接口
    async testAdmin() {
        const res = await http.get('/test/admin', {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // OSS
    // 获取上传token
    async getOssUploadToken() {
        const res = await http.get('/oss/get-upload-token', {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 获取订单列表
    async getOrderList(params: {
        currentPage?: number;
        pageSize?: number;
        orderStatus?: number;
        orderNo?: string;
        startTime?: string;
        endTime?: string;
        productName?: string;
    }) {
        debugger;
        const res = await http.post('/api/order/list', params, {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 根据ID获取订单详情
    async getOrderById(orderId: number) {
        const res = await http.get(`/api/order/${orderId}`, {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 更新订单状态
    async updateOrderStatus(params: {
        orderId: number;
        orderStatus: number;
        remark?: string;
    }) {
        const res = await http.post('/api/order/update/status', params, {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 删除订单
    async deleteOrder(orderId: number) {
        const res = await http.post(`/api/order/delete/${orderId}`, {}, {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }

    // 导出订单
    async exportOrder(params: {
        orderStatus?: number;
        orderNo?: string;
        startTime?: string;
        endTime?: string;
        productName?: string;
    }) {
        const res = await http.post('/order/export', params, {
            headers: {
                authorization: this.authorization
            }
        });
        return res;
    }


}

const ttOrderApi = new TtOrderApi();

export default ttOrderApi;

// 数据模型定义接口
export interface LoginRequest {
    username: string;
    password: string;
}

export interface LoginResponse {
    token: string;
    userId: number;
    username: string;
}

export interface RefreshTokenRequest {
    refreshToken: string;
}

export interface RefreshTokenResponse {
    token: string;
}

export interface GenerateTokenRequest {
    externalOrderNo?: string;
    userId?: string;
    username?: string;
    expiresIn?: number;
    extraParams?: Record<string, any>;
}

export interface GenerateTokenResponse {
    token: string;
    externalOrderNo?: string;
    h5Url?: string;
    expiresIn?: number;
    createdAt?: number;
}

export interface ExchangeTokenRequest {
    token: string;
    sign: string;
    extraParams?: any;
}

export interface TempToken {
    token: string;
    externalOrderNo?: string;
    userId?: string;
    username?: string;
    createdAt?: number;
    expiresAt?: number;
    extraParams?: string;
    jwtToken?: string;
    jwtExpiresAt?: number;
    orderSubmitted?: boolean;
    h5OrderId?: number;
}

export interface Font {
    fontId: number;
    fontName: string;
    fontType: string;
    fontFileUrl: string;
    fontImageUrl: string;
    status?: boolean;
    fontSort?: number;
    ifDel?: boolean;
    createTime?: string;
    updateTime?: string;
}

export interface DesignInfo {
    designId?: number;
    data?: string;
    picUrls?: string;
    sort?: number;
    ifShow?: boolean;
}

export interface ProductNegativeTemplateVO {
    templateId?: number;
    productNegativeId?: number;
    templateName?: string;
    sort?: number;
    ifShow?: boolean;
    designs?: DesignInfo[];
}

export interface SubmitDesignRequest {
    token?: string;
    productId: number;
    productNegativeId: number;
    skuId?: number;
    designData?: string;
    designName?: string;
    designImageUrl?: string;
    productShowImageUrl?: string;
    productSize?: string;
    productColor?: string;
    productNumber?: number;
    remark?: string;
}

export interface ApiResponse<T = any> {
    code: number;
    message: string;
    data: T;
}

export interface H5DesignOrderVO {
    orderId?: number;
    orderNo?: string;
    userId?: number;
    userIdentifier?: string;
    productId?: number;
    productName?: string;
    productNegativeId?: number;
    skuId?: number;
    skuName?: string;
    designData?: string;
    designName?: string;
    designImageUrl?: string;
    productShowImageUrl?: string;
    productSize?: string;
    productColor?: string;
    productNumber?: number;
    orderStatus?: number;
    orderStatusDesc?: string;
    remark?: string;
    createTime?: string;
    updateTime?: string;
}

// 分页结果接口
export interface PageResult<T> {
    currentPage: number;
    pageSize: number;
    total: number;
    totalPages: number;
    hasNext: boolean;
    hasPrevious: boolean;
    records: T[];
}

